#pragma once

#include <iostream>
#include <string>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>  // struct sockaddr_in

#include "Log.hpp"

#define PORT 8081
#define BACKLOG 10

class TcpServer
{
private:
    int port;
    int listen_sock;

    // 设置成为单例模式
    static TcpServer *tcp_server;
private:
    TcpServer(int _port = PORT):port(_port), listen_sock(-1)
    {}

    TcpServer(const TcpServer&){}
    
    ~TcpServer(){}
private:
    // 创建套接字
    void Socket()
    {
        listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if(listen_sock < 0){
            LOG(Fatal, "create socket error");
            exit(1);
        }
        int opt = 1;
        setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        LOG(Info, "create socket success");
    }
    // 绑定套接字
    void Bind()
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if(bind(listen_sock, (const sockaddr*)&local, sizeof(local)) < 0){
            LOG(Fatal, "bind socket error");
            exit(2);
        }
        LOG(Info, "bind socket success");
    }
    // 监听套接字
    void Listen()
    {
        if(listen(listen_sock, BACKLOG) < 0){
            LOG(Fatal, "lieten socket error");
            exit(3);
        }
        LOG(Info, "lieten socket success");
    }
    // 初始化TcpServer
    void InitTcpServer()
    {
        Socket();
        Bind();
        Listen();
        LOG(Info, "Init socket success");
    }
public:
    static TcpServer* GetInstance(int port)
    {
        static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
        if(tcp_server == nullptr){
            pthread_mutex_lock(&lock);
            if(tcp_server == nullptr){
                tcp_server = new TcpServer(port);
                tcp_server->InitTcpServer();
            }
            pthread_mutex_unlock(&lock);
        }
        return tcp_server;
    }
    // 获取 listen_sock 值
    int Sock()
    {
        return listen_sock;
    }
};

TcpServer *TcpServer::tcp_server = nullptr;